package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService{
    @Autowired
    private RoleMapper roleMapper;

    public void deleteByPrimaryKey(Long id) {
        //删除: 破坏关系
        roleMapper.deleteRelation(id);
        roleMapper.deleteByPrimaryKey(id);
    }

    public void insert(Role record) {
        roleMapper.insert(record);
        //获取权限对象
        List<Permission> permissions = record.getPermissions();
        if(permissions != null){
            for (Permission permission : permissions) {
                //维护与权限的关系
                roleMapper.insertRelation(record.getId(), permission.getId() );
            }
        }

    }

    public Role selectByPrimaryKey(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    public List<Role> selectAll() {
        return roleMapper.selectAll();
    }

    public void updateByPrimaryKey(Role record) {
        //删除: 破坏关系
        roleMapper.deleteRelation(record.getId());
        roleMapper.updateByPrimaryKey(record);
        //再维护关系
        //获取权限对象
        List<Permission> permissions = record.getPermissions();
        if(permissions != null){
            for (Permission permission : permissions) {
                //维护与权限的关系
                roleMapper.insertRelation(record.getId(), permission.getId() );
            }
        }

    }

    //分页
    public PageResult query(QueryObject qo){
        //查总数
        int total = roleMapper.queryForCount(qo);
         if(total==0){
             return new PageResult();
         }
         //查每页数据
        List<Role> rows = roleMapper.queryForList(qo);
        return new PageResult(rows,total);
    }
    public List<Long> getRoleIdByEmpId(Long empId) {
        return roleMapper.getRoleIdByEmpId(empId);
    }

    public List<String> queryRoleSnByEmpId(Long id) {
        return roleMapper.queryRoleSnByEmpId(id);
    }

    @Override
    public List<String> selectByEmpId(Long id) {
        return roleMapper.selectByEmpId(id);
    }

}
